import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '@/store'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    }
  ]
});

router.beforeEach((to, from, next) => {  
  const isLoggedIn = store.state.isLoggedIn;  
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);  
  const token = localStorage.getItem('loginState')
  if (requiresAuth && !isLoggedIn&&token=="") {  
    // 如果路由需要认证，但用户未登录，重定向到登录页面  
    console.log(isLoggedIn,requiresAuth)
    next('/login');  

  } else if (!requiresAuth && isLoggedIn && to.path === '/login'&&token!="") {  
    // 如果用户已登录，但尝试访问登录页面，重定向到系统首页  
    next('/');  
  } else {  
    // 否则，正常导航  
    next();  
  }  
});  

export default router
